package com.hnkywl.sts.service.kcgl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hnkywl.sts.dao.jhgl.BgjhhzmxDao;
import com.hnkywl.sts.dao.kcgl.ZkdDao;
import com.hnkywl.sts.dao.kcgl.ZkdmxDao;
import com.hnkywl.sts.dao.organ.CkDao;
import com.hnkywl.sts.dao.organ.GsjgDao;
import com.hnkywl.sts.dao.wlgl.XspsDao;
import com.hnkywl.sts.dao.xsgl.KhDao;
import com.hnkywl.sts.entity.organ.Ck;
import com.hnkywl.sts.entity.organ.Nbgs;
import com.hnkywl.sts.entity.xsgl.*;
import com.hnkywl.sts.service.base.BmService;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.util.ReflectionUtils;
import net.ruixin.orm.hibernate.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-5-9
 * Time: 下午9:07
 * To change this template use File | Settings | File Templates.
 */
@Service
public class ZkdService {
    private ZkdDao zkdDao;
    private ZkdmxDao zkdmxDao;
    private KhDao khDao;
    private BmService bmService;
    private CkDao ckDao;
    private BgjhhzmxDao bgjhhzmxDao;
    private GsjgDao gsjgDao;
    private XspsDao xspsDao;

    /**
     * 查询所有的转库单
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Transactional
    public String findAllZkd(String zkdh, int pageNo, int pageSize) {
        Page<Zkd> ZkdPage = this.zkdDao.findZkdList(zkdh, pageNo, pageSize);
        List<Zkd> ZkdList = ZkdPage.getResult() == null ? new ArrayList<Zkd>() : ZkdPage.getResult();
        return "{\"total\":" + ZkdPage.getTotalCount() + ",\"rows\":" + new GsonBuilder().setDateFormat("yyyy-MM-dd").create().toJson(ZkdList) + "}";
    }

    /**
     * 转库单明细
     *
     * @param zkdId
     * @return
     */
    public String findZkdmxDetail(Long zkdId) {
        Gson gson = new Gson();
        List<Map> zkdmxList = this.zkdDao.findZkdmxList(zkdId);
        Double zksl = 0d;
        String result = "";
//        if (zkdmxList.size() > 0) {
//            for (Map map : zkdmxList) {
//                zksl += map.get("zksl") == null ? 0f : (Double) map.get("zksl");
//            }
//            result = "{\"rows\":" + gson.toJson(zkdmxList) + ",\"footer\":[{\"wzgg.code\":\"合计:\",\"zksl\":" + zksl + "}]}";
//        } else {
        result = "{\"rows\":" + gson.toJson(zkdmxList) + "}";
        // }
        return result;
    }

    //实时库存查询转库单明细
    public String findSskcZkdmxDetail(Long khId) {
        Gson gson = new Gson();
        List<Map> zkdmxList = this.zkdDao.findSskcZkdmxList(khId);
        Double zksl = 0d;
        String result = "";
        result = "{\"rows\":" + gson.toJson(zkdmxList) + "}";
        return result;
    }

    @Transactional
    public void saveZkd(Zkd zkd) throws RuntimeException {
        zkd.setZkdh(bmService.getZkdhbm());
        zkd.setDateCreated(new Date());
        zkd.setLastUpdated(zkd.getDateCreated());
        zkd.setCreateUser(YgService.getCurrentYg());
        zkd.setCreateOrgan(YgService.getCurrentYg().getZggs());
        zkd.setCreateDepartment(YgService.getCurrentYg().getZgjg());
        zkd.setZt("ybc");
        this.zkdDao.save(zkd);
    }

    @Transactional
    public void updateZkd(Zkd zkd) throws RuntimeException {
        Zkd clone = this.zkdDao.get(zkd.getId());
        clone = (Zkd) ReflectionUtils.getInstance(clone, zkd);
        clone.setLastUpdated(new Date());
        this.zkdDao.save(clone);
    }

    @Transactional
    public void delZkd(Long zkdId) throws RuntimeException {
        Zkd zkd = this.zkdDao.get(zkdId);
        zkd.setDeleted(1);
        zkd.setLastUpdated(new Date());
        this.zkdDao.save(zkd);
        if (zkd.getZkdmxList() != null && zkd.getZkdmxList().size() != 0) {
            for (Zkdmx zkdmx : zkd.getZkdmxList()) {
                zkdmx.setDeleted(1);
                zkdmx.setLastUpdated(new Date());
                zkdmxDao.save(zkdmx);
            }
        }
    }

    /**
     * 提交
     *
     * @param id
     */
    @Transactional
    public void changeStatusTj(Long id) {
        Zkd zkd = this.findZkdDetail(id);
        zkd.setZt("ytj");
        zkd.setLastUpdated(new Date());
        this.zkdDao.save(zkd);
    }

    /**
     * 审批
     *
     * @param id
     */
    @Transactional
    public void changeStatus(Long id) {
        Zkd zkd = this.findZkdDetail(id);
        zkd.setZt("ysp");
        zkd.setLastUpdated(new Date());
        if (zkd.getZkdmxList() != null && zkd.getZkdmxList().size() != 0) {
            for (Zkdmx zkdmx : zkd.getZkdmxList()) {
                Kh ykh = khDao.get(zkdmx.getKh().getId());
                ykh.setKkdsl(ykh.getKkdsl() - zkdmx.getZksl());   //审批通过减去转出仓库的卡号的可开单数量
            }
        }
        this.zkdDao.save(zkd);
    }

    /**
     * 二级平衡 转库
     *
     * @param ckIds
     * @param khIds
     * @param phsls
     * @param dhckId
     */
    @Transactional
    public void ejphzk(String ckIds, String khIds, String phsls, Long dhckId, Long bgjhhzmxId) throws RuntimeException {
        Ck zrck = ckDao.get(dhckId);
        String[] ckids = ckIds.split(",");
        List<Ck> cks = new ArrayList<Ck>();
        for (int i = 0; i < ckids.length; i++) {
            Ck ck = ckDao.get(Long.parseLong(ckids[i]));
            cks.add(ck);
        }
        String[] khids = khIds.split(",");
        List<Kh> khs = new ArrayList<Kh>();
        for (int i = 0; i < khids.length; i++) {
            Kh kh = khDao.get(Long.parseLong(khids[i]));
            khs.add(kh);
        }
        String[] phslz = phsls.split(",");
        Boolean existZkd = zkdDao.existZkd(bgjhhzmxId);
        if (existZkd) {
            validZkd(bgjhhzmxId, phslz);
        } else {
            validZkdInTo(bgjhhzmxId, phslz, cks, zrck, khs);
        }

        double sum = 0d;
        for (String sl : phslz) {
            sum += Double.parseDouble(sl);
        }
        bgjhhzmxDao.updatesl2(sum, bgjhhzmxId);
    }

    private void validZkd(Long bgjhhzmxId, String[] phslz) throws RuntimeException {
        List<Zkd> zkdList = zkdDao.findZkdByBgjhhzmxId(bgjhhzmxId);
        for (Zkd zkd : zkdList) {
            if ("ysp".equals(zkd.getZt())) {
                throw new RuntimeException("此保供计划汇总存在转库单，并且已审批");
            }
            List<Zkdmx> zkdmxes = zkd.getZkdmxList();
            zkd.setLastUpdated(new Date());
            for (int i = 0; i < zkdmxes.size(); i++) {
                zkdmxes.get(i).setZksl(Double.parseDouble(phslz[i]));
                zkdmxes.get(i).setLastUpdated(new Date());
                zkdmxDao.save(zkdmxes.get(i));
            }
            zkdDao.save(zkd);
        }
    }

    private void validZkdInTo(Long bgjhhzmxId, String[] phslz, List<Ck> cks, Ck zrck, List<Kh> khs) {
        //二级平衡转库
        for (int i = 0; i < cks.size(); i++) {
            Zkd zkd = new Zkd();
            zkd.setType("bgzk");
            zkd.setZcck(cks.get(0));
            zkd.setZrck(zrck);
            zkd.setSqgs((Nbgs) gsjgDao.get(bgjhhzmxDao.get(bgjhhzmxId).getBgjhhz().getLj().getJyjg().getId()));
            zkd.setBgjhhzmx(bgjhhzmxDao.get(bgjhhzmxId));
            zkd.setZkdh(bmService.getZkdhbm());
            zkd.setZt("ybc");
            zkd.setCreateUser(YgService.getCurrentYg());
            zkd.setCreateOrgan(YgService.getCurrentYg().getZggs());
            zkd.setCreateDepartment(YgService.getCurrentYg().getZgjg());
            zkd.setLastUpdated(new Date());
            List<Zkdmx> zkdmxList = new ArrayList<Zkdmx>();
            Zkdmx zkdmx = new Zkdmx();
            zkdmx.setKh(khs.get(i));
            zkdmx.setZkd(zkd);
            zkdmx.setZksl(Double.parseDouble(phslz[i]));
            zkdmx.setCreateUser(YgService.getCurrentYg());
            zkdmx.setCreateOrgan(YgService.getCurrentYg().getZggs());
            zkdmx.setCreateDepartment(YgService.getCurrentYg().getZgjg());
            zkdmx.setLastUpdated(new Date());
            zkd.setZkdmxList(zkdmxList);
            zkdmxDao.save(zkdmx);
            zkdDao.save(zkd);
        }
    }

    /**
     * 转库调用的方法
     *
     * @param zksq
     */
    @Transactional
    public void zk(Zkd zksq) {
        Zkd zkd = this.findZkdDetail(zksq.getId());
        zkd.setZkrq(new Date());
        zkd.setLastUpdated(new Date());
        zkd.setZt("yzc");
        zkd.setCkr(YgService.getCurrentYg());
        this.zkdDao.save(zkd);

        for (Zkdmx zkdmx : zksq.getZkdmxList()) {
            Kh ykh = khDao.get(zkdmx.getKh().getId()); //找出原卡号
            if (ykh.getJs() != null && zkdmx.getZcjs() != null) {
                ykh.setJs(ykh.getJs() - zkdmx.getZcjs());//将原卡号里的件数减去转出的件数
            }
            ykh.setSl(ykh.getSl() - zkdmx.getZcsl()); //将原卡号里的数量减去转出的数量
            ykh.setKkdsl(ykh.getKkdsl() + zkdmx.getZksl() - zkdmx.getZcsl());//重置原卡号的可开单数量
            initKh(ykh);
            ykh.setLastUpdated(new Date());
            khDao.save(ykh);
            zkdmx.setZkd(zkd);
            zkdmxDao.save(zkdmx);
        }
    }

    //转入
    @Transactional
    public void zr(Zkd zksq) {
        Zkd zkd = this.findZkdDetail(zksq.getId());
        zkd.setZrrq(new Date());
        zkd.setLastUpdated(new Date());
        zkd.setZt("yzr");
        this.zkdDao.save(zkd);

        for (Zkdmx zkdmx : zksq.getZkdmxList()) {
            Kh ykh = khDao.get(zkdmx.getKh().getId()); //找出原卡号
            Kh nkh = new Kh();//复制原卡号
            nkh = (Kh) ReflectionUtils.getInstance(nkh, ykh);
            nkh.setId(null);//将新卡号ID置空
            nkh.setKhbm(bmService.getKckhbm(zkd.getZrck().getId()));
            if (nkh.getJs() != null) {
                nkh.setJs(zkdmx.getZrjs());//新卡号的设置转入的件数
            }
            nkh.setKkdsl(zkdmx.getZrsl());//新卡号设置可开单的数量为转入的数量
            nkh.setSl(zkdmx.getZrsl());//新卡号设置数量为转入的数量
            nkh.setCk(zkd.getZrck());//新卡号设置仓库
            nkh.setXsmxList(null);
            nkh.setCreateUser(YgService.getCurrentYg());
            nkh.setCreateOrgan(YgService.getCurrentYg().getZggs());
            nkh.setCreateDepartment(YgService.getCurrentYg().getZgjg());
            nkh.setLastUpdated(new Date());
            zkdmx.setZkd(zkd);
            khDao.save(nkh);
            zkdmx.setNewkh(nkh);
            zkdmxDao.save(zkdmx);
        }
    }

    /**
     * 查询销售单费用
     *
     * @param zkdId
     * @return
     */
    public String findZkfyDetail(Long zkdId) {
        Gson gson = new Gson();
        String result = "";
        Double jfsl = 0d;
        Double je = 0d;
        List<Map> zkdfyList = this.zkdDao.findZkfyList(zkdId);
        if (zkdfyList.size() > 0) {
            for (Map map : zkdfyList) {
                jfsl += map.get("jfsl") == null ? 0d : Double.parseDouble(map.get("jfsl").toString());
                je += map.get("je") == null ? 0d : Double.parseDouble(map.get("je").toString());
            }
            result = "{\"rows\":" + gson.toJson(zkdfyList) + ",\"footer\":[{\"fylb.fykmjc\":\"合计:\",\"jfsl\":" + jfsl
                    + ",\"je\":" + je + "}]}";
        } else {
            result = "{\"rows\":" + gson.toJson(zkdfyList) + "}";
        }
        return result;
    }

    private void initKh(Kh kh) {
        if (kh.getXsmxList() != null && kh.getXsmxList().size() == 0) {
            kh.setXsmxList(null);
        }
    }

    @Transactional
    public void saveZkdPs(Psd zkps) throws SQLException {
        zkps.setPsdh(this.bmService.getPsdbm());
        zkps.setDateCreated(new Date());
        zkps.setCreateUser(YgService.getCurrentYg());
        zkps.setCreateOrgan(YgService.getCurrentYg().getZggs());
        zkps.setCreateDepartment(YgService.getCurrentYg().getZgjg());
        zkps.setLastUpdated(zkps.getDateCreated());
        Zkd zkd = zkdDao.get(zkps.getZkd().getId());
        zkd.setYps(true);
        zkd.setPsd(zkps);
        zkps.setZkd(zkd);
        this.xspsDao.save(zkps);
        this.zkdDao.save(zkd);
    }

    @Transactional
    public Zkd findZkdDetail(Long id) {
        return this.zkdDao.get(id);
    }

    @Autowired
    public void setZkdDao(ZkdDao zkdDao) {
        this.zkdDao = zkdDao;
    }

    @Autowired
    public void setZkdmxDao(ZkdmxDao zkdmxDao) {
        this.zkdmxDao = zkdmxDao;
    }

    @Autowired
    public void setKhDao(KhDao khDao) {
        this.khDao = khDao;
    }

    @Autowired
    public void setBmService(BmService bmService) {
        this.bmService = bmService;
    }

    @Autowired
    public void setCkDao(CkDao ckDao) {
        this.ckDao = ckDao;
    }

    @Autowired
    public void setBgjhhzmxDao(BgjhhzmxDao bgjhhzmxDao) {
        this.bgjhhzmxDao = bgjhhzmxDao;
    }

    @Autowired
    public void setGsjgDao(GsjgDao gsjgDao) {
        this.gsjgDao = gsjgDao;
    }

    @Autowired
    public void setXspsDao(XspsDao xspsDao) {
        this.xspsDao = xspsDao;
    }
}
